package com.itstorm.pomeloweather.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.widget.Toast;

public class LocationUtils {

	public static String getAddress(Context context) {

		LocationManager locationManager;
		Double longitude;
		Double latitude;
		String serviceName = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) context.getSystemService(serviceName);
		// 查找到服务信息
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗

		String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
		Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置

		longitude = location.getLongitude();
		latitude = location.getLatitude();

		String url = "http://maps.google.com/maps/api/geocode/json?latlng="
				+ latitude + "," + longitude + "&language=zh_CN&sensor=false";
		HttpClient client = new DefaultHttpClient();
		StringBuilder sb = new StringBuilder();
		try {
			HttpResponse resp = client.execute(new HttpGet(url));
			HttpEntity he = resp.getEntity();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					he.getContent()));
			String str = "";
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			JSONObject jo1 = new JSONObject(sb.toString());
			String str1 = jo1.getString("results");
			JSONArray arr1 = new JSONArray(str1);
			String str2 = arr1.get(0).toString();
			JSONObject jo2 = new JSONObject(str2);
			String str3 = jo2.getString("formatted_address");
			Toast.makeText(context, str3, Toast.LENGTH_LONG).show();
			return str3;

		} catch (JSONException e) {
			return "error";
		}
	}

}
